package com.yqz.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.yqz.common.CodeMsg;
import com.yqz.common.exception.BussiException;
import com.yqz.common.util.WebUtil;
import com.yqz.sys.domain.CompUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CompUser currentCompUser = WebUtil.getCurrentCompUser();
        if(currentCompUser != null){
            return true;
        }
        String ajaxHeader = request.getHeader("X-Requested-With");
        boolean ajaxFlag =  StrUtil.equals(ajaxHeader,"XMLHttpRequest");
        if(!ajaxFlag){
            response.sendRedirect(request.getContextPath() + "/redirect.jsp");
        } else {
            throw new BussiException(CodeMsg.PERM_USER_LOGIN_INVALID_ERROR.CODE,CodeMsg.PERM_USER_LOGIN_INVALID_ERROR.MSG);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
